package com.lipaluma.field.validator;

import java.util.List;
import java.util.Stack;

/**
 * Validator that marks the start of the chain of the validations
 * 
 * @author Mario
 */
public class ChainValidator extends Stack<Validator> {
	private static final long serialVersionUID = -8703275017752528687L;

	private boolean required = false;

	public ChainValidator(boolean required) {
		this.required = required;
	}
	
//	public boolean init(Context context, Field field) {
//		this.required = required || context.isRequired(field) || field.isAnnotationPresent(Required.class);
//		return true;
//	}
//
//	public boolean init(Context context, Field field, Element element) {
//		this.required = context.isRequired(field, element);
//		return true;
//	}

	public boolean validate(Object value, List<ValidationError> errors) {
		if(value == null) {
			if(required) {
				errors.add(new ValidationError("The value is required and null value is encountered."));
				return false;
			} else {
				return true;
			}
		}

		boolean result = true;
		if(this.isEmpty())
			return result;
		for (Validator validator : this) {
			result &= validator.validate(value, errors);
		}
		return result;
	}
	
	/**
	 * Reset validators if they are {@link Resetable}
	 */
	public void reset() {
		for (Validator validator : this) {
			if(Resetable.class.isAssignableFrom(validator.getClass()))
				((Resetable)validator).reset();
		}
	}
	
	public void setRequired(boolean required) {
		this.required = required;
	}
}
